<template>
    <view>
        <scroll-view
                class="scrollView"
                scroll-y
                :style="{height:`calc(100vh - ${footHeight}rpx)`}"
                :scroll-into-view="scrollToView"
        >
            <view class="list" :style="{opacity:listShow}">
                <view class="li" v-for="(item,index) in list" :key="index">
                    <view class="time" v-if="shouldShowTime(index)">{{$common.formatTimeChat(item.create_time * 1000)}}</view>
                    <view class="leftMain" :class="('user-' + userInfo.id) == item.to_user_id ? '' : 'rightMain'">
                        <image class="head" v-if="('user-' + userInfo.id) == item.to_user_id" :src="item.avatar ? item.avatar : '../../static/img/logo_app.png'"></image>
                        <image class="head" v-else :src="userInfo.avatar ? userInfo.avatar : '../../static/img/logo_app.png'"></image>
                        <view class="word" v-if="item.type == 0">
                            {{item.content}}
                        </view>
                        <view class="conImg" v-if="item.type == 1">
                            <image :src="item.content" mode="widthFix"></image>
                        </view>
                        <view class="conImg" v-if="item.type == 2" @click="VideoShowClick(item)">
                            <image :src="item.content.indexOf('videoUrl') != -1 ? JSON.parse(item.content).cover : ''" mode="widthFix"></image>
                            <view class="hidden">
                                <image src="../../static/img/icon50.png"></image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view id="chatWindowBtm"></view>
        </scroll-view>
        <db-getTitlecover :tempFilePath="tempFilePath" :s="4" />
        <view class="footer" :style="{height: footHeight + 'rpx'}">
            <view class="top">
                <view class="fl">
                    <input type="text" @confirm="inputConfirm" v-model="message" placeholder="请输入">
                </view>
                <view class="fr" @click="changeHeight">
                    <image src="../../static/img/icon46.png"></image>
                </view>
            </view>
            <view class="btm">
                <view class="li" @click="selectPic">
                    <view class="h1">
                        <image src="../../static/img/icon47.png"></image>
                    </view>
                    <view class="h2">
                        照片
                    </view>
                </view>
                <view class="li" @click="takePhotos">
                    <view class="h1">
                        <image src="../../static/img/icon48.png"></image>
                    </view>
                    <view class="h2">
                        拍照
                    </view>
                </view>
                <view class="li" @click="chooseVideo">
                    <view class="h1">
                        <image src="../../static/img/icon49.png"></image>
                    </view>
                    <view class="h2">
                        视频
                    </view>
                </view>
            </view>
        </view>
        <u-popup :show="VideoShow" @close="VideoPopclose" @open="VideoPopOpen" mode="center" :safeAreaInsetBottom="false" closeable>
            <view class="videoBox">
                <video :src="popupVideoUrl" autoplay></video>
            </view>
        </u-popup>
    </view>
</template>

<script>
    /*import {
        getAuth,
        chatGetList
    } from '../../api/api'*/
    import {base64ToPath} from "image-tools"
    import userInfo from "../user/userInfo";
    export default {
        data() {
            return {
                footHeight:125,
                message:'',
                list:[],
                userInfo:'',
                scrollToView:'',
                listShow:0,
                id:'',
                itemData:'',

                tempFilePath:null,
                videoUrl:'',
                popupVideoUrl:'',
                VideoShow:false,
                isAutoplay:false,
                shopName:''
            }
        },
        onLoad(options) {
            this.id = options.id;
            this.shopName = options.shopName;
            uni.setNavigationBarTitle({
                title: this.shopName
            });
            console.log(this.id);

            uni.$on('res', (
                frame
            ) => {
                base64ToPath(frame).then(path=>{
                    const loc_path = plus.io.convertLocalFileSystemURL(path)
                    this.$common.upLoadImg(loc_path).then(data => {
                        setTimeout(() => {
                            let content = {
                                videoUrl:this.videoUrl,
                                cover:data.data.complete_url
                            }
                            let item = {...this.list[this.list.length - 1]};
                            item.aid = item.aid + 1;
                            item.content = JSON.stringify(content);
                            item.type = 2;
                            item.to_user_id = `consumer-${this.id}`;
                            let timestampInMilliseconds = Date.now();
                            item.create_time = Math.floor(timestampInMilliseconds / 1000);
                            this.list.push(item);
                            this.scrollToView = '';
                            setTimeout(() => {
                                this.scrollToView = 'chatWindowBtm';
                            },50)

                            this.globalajax('chat/getAuth',{
                                toid:`consumer-${this.id}`,
                                content:item.content,
                                type:2,
                                source:2
                            },'POST',res => {
                                console.log(res);
                            })
                        },500)
                    })
                })
            })
        },
        onShow(){
            // this.userInfo = uni.getStorageSync('auth_info');
            // console.log(this.userInfo);

            this.getUserInfo();
        },
        methods: {
            // 判断是否显示时间
            shouldShowTime(index) {
                if (index === 0) {
                    // 第一条数据直接显示
                    return true;
                }
                const currentTime = new Date(this.list[index].create_time * 1000).getTime();
                const prevTime = new Date(this.list[index - 1].create_time * 1000).getTime();
                console.log(currentTime - prevTime > 30 * 60 * 1000);
                // 判断时间间隔是否超过30分钟（30 * 60 * 1000 毫秒）
                return currentTime - prevTime > 30 * 60 * 1000;
            },
            getUserInfo() {
                var a = this
                a.globalajax('user/info', {}, 'GET', function(res) {
                    console.log(res);
                    if (res.data.code == 200) {
                        if(res.data.data.info.status==0){
                            // 账号被拉黑   清除token
                            uni.clearStorageSync()
                            uni.reLaunch({
                                url: '/pages/index/login'
                            })
                        }else{
                            a.userInfo = res.data.data.info;
                            console.log(a.userInfo);
                            a.chatGetListFun();
                        }
                    } else {
                        a.$showModal({
                            title:'友情提示',
                            content:res.data.msg,
                            showCancel:false,
                            confirmText:'我知道了',
                            success: (res) => {
                            }
                        });
                    }
                });
            },
            VideoShowClick(item){
                this.popupVideoUrl = JSON.parse(item.content).videoUrl;
                this.VideoShow = true;
            },
            VideoPopclose(){
                this.VideoShow = false;
            },
            VideoPopOpen(){
                /*setTimeout(() => {
                    this.isAutoplay = true;
                },200)*/
            },
            saveBase64ToFile(base64) {
                return new Promise((resolve, reject) => {
                    // 去掉 base64 前缀（如 "data:image/png;base64,"）
                    const base64Content = base64.split(',')[1]

                    // 生成随机文件路径
                    const filePath = this.generateRandomFilePath()

                    // 将 base64 数据保存为文件
                    plus.io.writeFile({
                        path: filePath, // 保存路径
                        data: base64Content,
                        encoding: 'base64',
                        success: () => {
                            resolve(filePath) // 返回文件路径
                        },
                        fail: (err) => {
                            reject(err)
                        },
                    })
                })
            },
            generateRandomFilePath() {
                const timestamp = Date.now() // 时间戳
                const randomString = Math.random().toString(36).substring(2, 8) // 随机字符串
                const fileName = `file_${timestamp}_${randomString}.png` // 文件名
                return `_doc/${fileName}` // 文件路径
            },
            getPurePath(path){
                const prefix = 'file://'
                const relativeRrefix = '_doc/'
                if (path.includes(prefix)) {
                    path = path.replace(prefix, '')
                }
                if (path.includes(relativeRrefix)) {
                    path = plus.io.convertLocalFileSystemURL(path)
                }
                return path
            },
            chooseVideo() {
                var that = this
                uni.chooseVideo({
                    compressed: true,
                    extension: ['mp4'],
                    success: function(
                        {
                            tempFilePath,
                            duration,
                            tempFile
                        }
                    ) {
                        that.$common.upLoadImg(tempFilePath).then(data => {
                            console.log(data);
                            that.videoUrl = data.data.complete_url;
                        })
                        // #ifdef APP
                        const idx = tempFilePath.lastIndexOf('.');
                        const videoType = tempFilePath.slice(idx + 1);
                        if (tempFilePath.includes('_doc/')) {
                            tempFilePath = `file://${plus.io.convertLocalFileSystemURL(tempFilePath)}`;
                            console.log(tempFilePath);
                        }
                        // #endif
                        that.tempFilePath = tempFilePath;
                        console.log(tempFilePath);
                    },
                    fail: function(err) {
                        console.log(err);
                        reject(err);
                    }
                });
            },
            takePhotos(){
                uni.chooseImage({
                    count: 9,
                    sourceType:['camera'],
                    success:(res) => {
                        this.$common.upLoadImg(res.tempFilePaths[0]).then(data => {
                            let item = {...this.list[this.list.length - 1]};
                            item.aid = item.aid + 1;
                            item.content = data.data.complete_url;
                            item.type = 1;
                            item.to_user_id = `consumer-${this.id}`;
                            let timestampInMilliseconds = Date.now();
                            item.create_time = Math.floor(timestampInMilliseconds / 1000);
                            this.list.push(item);
                            this.scrollToView = '';
                            console.log(this.list);
                            setTimeout(() => {
                                this.scrollToView = 'chatWindowBtm';
                            },50)

                            this.globalajax('chat/getAuth',{
                                toid:`consumer-${this.id}`,
                                content:item.content,
                                type:1,
                                source:2
                            },'POST',res => {
                                console.log(res);
                            })
                        })
                    }
                })
            },
            selectPic(){
                console.log(91);
                uni.chooseImage({
                    count: 9,
                    sourceType:['album'],
                    success:(res) => {
                        this.$common.upLoadImg(res.tempFilePaths[0]).then(data => {
                            console.log(data);
                            let item = {...this.list[this.list.length - 1]};
                            item.aid = item.aid + 1;
                            item.content = data.data.complete_url;
                            item.type = 1;
                            item.to_user_id = `consumer-${this.id}`;
                            let timestampInMilliseconds = Date.now();
                            item.create_time = Math.floor(timestampInMilliseconds / 1000);
                            this.list.push(item);
                            this.scrollToView = '';
                            console.log(this.list);
                            setTimeout(() => {
                                this.scrollToView = 'chatWindowBtm';
                            },50)

                            this.globalajax('chat/getAuth',{
                                toid:`consumer-${this.id}`,
                                content:item.content,
                                type:1,
                                source:2
                            },'POST',res => {
                                console.log(res);
                            })
                        })
                    }
                })
            },
            changeHeight(){
                if(this.footHeight == 125){
                    this.footHeight = 365;
                } else{
                    this.footHeight = 125;
                }
                this.scrollToView = '';
                setTimeout(() => {
                    this.scrollToView = 'chatWindowBtm';
                },50)
            },
            chatGetListFun(){
                this.globalajax('chat/getList',{
                    toid:`consumer-${this.id}`,
                    user_id:`user-${this.userInfo.id}`,
                    source:2,
                    size:1000
                },'POST',res => {
                    console.log(res);
                    this.scrollToView = '';
                    this.list = res.data.data;
                    console.log(this.list);
                    this.itemData = {...this.list[this.list.length - 1]};
                    setTimeout(() => {
                        this.listShow = 1;
                        this.scrollToView = 'chatWindowBtm';
                    },50)
                })
                /*chatGetList({
                    toid:this.id,
                    user_id:`consumer-${this.userInfo.id}`,
                    source:1,
                    size:1000
                }).then(res => {
                    console.log(res);
                    this.scrollToView = '';
                    this.list = res.data;
                    this.itemData = {...this.list[this.list.length - 1]};
                    setTimeout(() => {
                        this.listShow = 1;
                        this.scrollToView = 'chatWindowBtm';
                    },50)
                })*/
            },
            inputConfirm(){
                let item = {...this.list[this.list.length - 1]};
                item.aid = item.aid + 1;
                item.content = this.message;
                item.type = 0;
                item.to_user_id = `consumer-${this.id}`;
                let timestampInMilliseconds = Date.now();
                item.create_time = Math.floor(timestampInMilliseconds / 1000);
                console.log(item);
                this.list.push(item);
                this.scrollToView = '';
                console.log(this.list);
                setTimeout(() => {
                    this.scrollToView = 'chatWindowBtm';
                },50);
                this.message = '';

                this.globalajax('chat/getAuth',{
                    toid:`consumer-${this.id}`,
                    content:item.content,
                    type:0,
                    source:2
                },'POST',res => {
                    console.log(res);
                })
            }
        }
    }
</script>
<style>
    page{
        background: #efefef;
    }
</style>
<style lang="scss" scoped>
    .scrollView{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        .list{
            padding: 25rpx;
            .li{
                margin-top: 35rpx;
                &:first-child{
                    margin-top: 0;
                }
                .leftMain{
                    display: flex;
                    .head{
                        width: 70rpx;
                        height: 70rpx;
                        border-radius: 50%;
                    }
                    .word{
                        max-width: 530rpx;
                        background: #fff;
                        border-radius: 20rpx;
                        box-sizing: border-box;
                        padding: 20rpx;
                        font-size: 32rpx;
                        color: #222;
                        line-height: 46rpx;
                        margin: 0 20rpx;
                    }
                    .conImg{
                        border-radius: 15rpx;
                        position: relative;
                        margin: 0 20rpx;
                        position: relative;
                        image{
                            width: 260rpx;
                            border-radius: 15rpx;
                        }
                        .hidden{
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                            background: rgba(0,0,0,0.2);
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            image{
                                width: 80rpx;
                                height: 80rpx;
                            }
                        }
                    }
                    .conVideo{
                        video{
                            max-width: 360rpx;
                            max-height: 360rpx;
                            border-radius: 15rpx;
                        }
                    }
                }
                .rightMain{
                    flex-direction: row-reverse;
                }
                .time{
                    font-size: 20rpx;
                    color: #888;
                    text-align: center;
                    margin: 30rpx 0;
                }
            }
        }
    }
    .footer{
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #f6f6f6;
        border-top: 1px solid #ededed;
        transition: 0.3s;
        /*height: 365rpx;*/
        height: 125rpx;
        box-sizing: border-box;
        .top{
            height: 125rpx;
            padding: 0 25rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .fl{
                flex: 1;
                input{
                    height: 85rpx;
                    border-radius: 25rpx;
                    font-size: 28rpx;
                    color: #222;
                    padding: 0 25rpx;
                    background: #fff;
                }
            }
            .fr{
                padding-left: 25rpx;
                image{
                    width: 50rpx;
                    height: 50rpx;
                }
            }
        }
        .btm{
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            padding: 30rpx 25rpx 30rpx 25rpx;
            .li{
                width: 25%;
                .h1{
                    width: 120rpx;
                    height: 120rpx;
                    border-radius: 15rpx;
                    background: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    image{
                        width: 60rpx;
                        height: 60rpx;
                    }
                }
                .h2{
                    width: 120rpx;
                    text-align: center;
                    font-size: 28rpx;
                    color: #5c5c5c;
                    height: 60rpx;
                    line-height: 60rpx;
                }
            }
        }
    }
    .videoBox{
        width: 750rpx;
        height: 80vh;
        video{
            width: 100%;
            height: 100%;
        }
    }
</style>
